<template>
    <div class="login-wrap">
        <div class="ms-login">
            <div class="ms-title">{{projectTitle}}</div>
            <el-form  size="small" :model="param" :rules="rules" class="ms-content" v-show="login_type =='account'" label-width="0px" ref="login">
                <el-form-item prop="account_set_sid" v-if="showAccountSet">
                    <el-input size="small" placeholder="请输入账套号" tabindex="1" v-model="param.account_set_sid">
                        <el-button size="small" icon="el-icon-date" slot="prepend"></el-button>
                    </el-input>
                </el-form-item>
                <el-form-item prop="login_id">
                    <el-input size="small" placeholder="请输入登录账户" tabindex="1" v-model="param.login_id">
                        <el-button size="small" icon="el-icon-lx-people" slot="prepend"></el-button>
                    </el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input size="small" @keyup.enter.native="submitForm()" placeholder="请输入登录密码" tabindex="2"
                              type="password" v-model="param.password" show-password>
                        <el-button size="small" icon="el-icon-lx-lock" slot="prepend"></el-button>
                    </el-input>
                </el-form-item>
                <el-form-item prop="verifyCode" class="verifyCode">
                    <el-input size="small" @keyup.enter.native="submitForm()" placeholder="请输入验证码" tabindex="3"
                              type="text" v-model="param.verifyCode">
                        <!-- <el-button icon="el-icon-key" slot="prepend"></el-button> -->
                        <el-button size="small" slot="prepend" icon="el-icon-search"></el-button>
                        <img :src="verifyCodeUrl" slot="append" title="点击刷新" alt="" class="verify_img"
                                  @click="refreshVerifyCode" />
                    </el-input>
                </el-form-item>
                <el-checkbox tabindex="3" size="medium" v-model="remember">记住密码</el-checkbox>
                <div class="login-btn">
                    <el-button  size="medium" :loading="isLoginning" @click="submitForm()" type="primary">登 录</el-button>
                    <el-button  size="medium" @click="toReg()" v-if="false" type="info" plain class="toReg">还没有账套？我要“注册账套”</el-button>
                </div>
            </el-form>
            <div id="wxQrCode" v-show="login_type=='wx'" style="width: 300px;height: 400px;margin-left: 25px;"></div>
            <div class="loginType"><span @click="changeType('account')"   v-show="login_type!=='account'">账密登录</span>
                <span @click="changeType('wx')"  v-show="false">微信登录</span>
                <el-alert v-if="false"
                    title="体验账套：test"
                    description="体验账号：test 密码：Tsd123456  管理员账号：admin，登录密码：tyadmin123" :closable="false"
                    type="info">
                </el-alert>
            </div>
            <!--login_type!=='wx'-->
            </div>
        <div id="bottom_layer" class="s-bottom-layer s-isindex-wrap">
            <div class="s-bottom-layer-content">
                <p class="lh"><a class="text-color" href="https://beian.miit.gov.cn" target="_blank">粤ICP备18117831号</a></p>
                <p class="lh"><span class="text-color">©2022&nbsp;广州希尔浦软件科技有限公司&nbsp;</span></p>
            </div>
        </div>
        <div id="service_qr_lay" >
            <img :src="serviceQr" style="width: 100px;">
            <div style="width:100px;font-size: 1.2em;padding-top: 0.2em;padding-left: 1.5em;">联系客服</div>
        </div>
        <!-- <div class="ms-login download_area">
            <div class="ms-content">
                <el-image :src="downloadImgUrl" v-if="showDownload"></el-image>
                <span class="download_tips" @click="showDownload = !showDownload">点击下载APP</span>
            </div>
        </div> -->
    </div>
</template>

<script>
    import common from '@common/api/common';
    import apiConstants from "@common/api/constants";
    import anonApi from "@common/api/anonApi";
    import md5 from 'js-md5';
    import {AES} from '@common/utils/crypto';
    import NProgress from 'nprogress';
    import downloadImg from '@common/assets/img/download.png';
    import wxLogin from '@common/components/wx/wxLogin';
    import serviceQrImage from '@common/assets/img/service.png';
    import ModifyPwdForm from "@common/views/system/dialog/ModifyPwdForm.vue";
    //2020-10-09 二维码对应的URL是：http://www.szmingxiang.com/download4.0/app.html

    export default {
        data: function () {
            return {
                OP_WX_LOGIN:'wx_login',
                login_type:'account',
                has_wxqr:false,
                has_account:false,
                wxLogin_setting:undefined,
                param: {
                    account_set_sid:'',
                    login_id: '',
                    password: '',
                    verifyCode: '',
                },
                isLoginning: false,
                remember: false,
                rules: {
                    account_set_sid: [{required: true, message: '请输入账套号', trigger: 'blur'}],
                    login_id: [{required: true, message: '请输入登录账户', trigger: 'blur'}],
                    password: [{required: true, message: '请输入登录密码', trigger: 'blur'}],
                    verifyCode: [{required: true, message: '请输入验证码', trigger: 'blur'}],
                },
                downloadImgUrl: downloadImg,
                showDownload: false,
                verifyBaseUrl: `${window.configs.requestPrefix}${apiConstants.API_GetVerifyCode}?width=80&height=24&fontSize=24`,
                verifyCodeUrl: '',
                projectTitle:window.configs.projectTitle,
                serviceQr:serviceQrImage,
            };
        },
        computed: {
            showAccountSet() {
                return this.$utils.isEmpty(window.configs.account_set_sid);
            },
        },
        mounted () {
            let $this = this;
            if (!$this.showAccountSet) {
                $this.$utils.setLocalStorage($this.$store.state.accountSetSid, window.configs.account_set_sid);
            }
            NProgress.done();
            this.$utils.removeSessionStorage(this.$store.state.vuexName);
            let op = this.$route.query.op;
            if (this.OP_WX_LOGIN===op){
                let code = this.$route.query.code;
                let state = this.$route.query.state;
                let subData = {code,state};
                anonApi.wxLogin(subData, (result) => {
                    let userInfo = result.data;
                    $this.loginSuccess(userInfo);
                });
            }else{
                this.refreshVerifyCode();
                this.init();
                // this.initWeixinQrCode();
            }
        },
        methods: {
            // 初始化
            init () {
                let $this = this;
                // 记录密码渲染
                let userStr = $this.$utils.getLocalStorage($this.$store.state.rememberUser);
                if (userStr) {
                    $this.remember = true;
                    let userRemember = JSON.parse(userStr);
                    $this.param.login_id = userRemember.login_id;
                    $this.param.password = AES.de(userRemember.password);
                }
                $this.param.account_set_sid = $this.$utils.getAccountSetSid();
                let code = this.$route.query.code;
                if (code){
                    $this.param.account_set_sid = code
                }
                $this.param = $.extend({},$this.param)
            },
            refreshVerifyCode() {
                let $this = this;
                let url = `${$this.verifyBaseUrl}&v=${new Date().getTime()}`;
                common.getData(url, res => {
                    let blob = new Blob([res]);
                    $this.verifyCodeUrl = window.URL.createObjectURL(blob);
                });
            },
            initWeixinQrCode(){
                let $this = this;
                anonApi.getWeixinOpenSetting({}, res => {
                    let data = res.data;
                    $this.has_wxqr = data && data.login_wx ==1;
                    $this.wxLogin_setting = data;
                    if ($this.has_wxqr){
                        wxLogin(document,{
                            self_redirect: false,//true：手机点击确认登录后可以在 iframe 内跳转到 redirect_uri，false：手机点击确认登录后可以在 top window 跳转到 redirect_uri。默认为 false。
                            id: "wxQrCode",//第三方页面显示二维码的容器id
                            appid: $this.wxLogin_setting.wx_open_appid,//应用唯一标识，在微信开放平台提交应用审核通过后获得
                            scope: 'snsapi_login',//应用授权作用域，拥有多个作用域用逗号（,）分隔，网页应用目前仅填写snsapi_login即可
                            redirect_uri: encodeURIComponent("http://www.guwen.biz/#/login?op="+$this.OP_WX_LOGIN),//重定向地址，需要进行UrlEncode
                            state: new Date().getTime(),//用于保持请求和回调的状态，授权请求后原样带回给第三方。该参数可用于防止csrf攻击（跨站请求伪造攻击），建议第三方带上该参数，可设置为简单的随机数加session进行校验
                            style: 'black',//提供"black"、"white"可选，默认为黑色文字描述。
                            href: '' //自定义样式链接，第三方可根据实际需求覆盖默认样式。
                        });
                    }
                });
            },
            changeType(type){
                this.login_type = type;
            },
            submitForm () {
                let $this = this;
                if ($this.isLoginning) {
                    return;
                }
                $this.isLoginning = true;
                this.$refs.login.validate(valid => {
                    if (valid) {
                        anonApi.checkAccountSet({account_set_sid:$this.param.account_set_sid}, () => {
                            $this.$utils.setLocalStorage($this.$store.state.accountSetSid, $this.param.account_set_sid);
                            let verifySessionId = $this.$utils.getSessionStorage('VerifySession');
                            let subData = $.extend({}, $this.param);
                            if ($this.$utils.isNotEmpty(verifySessionId)) {
                                subData.verifySessionId = verifySessionId;
                            }
                            subData.password = md5(subData.password);
                            common.login(subData, result => {
                                let userInfo = result.data;
                                $this.loginSuccess(userInfo);
                            }, error => {
                                $this.isLoginning = false;
                                $this.$message.error(error.message);
                                if (error.code !== 102) {
                                    $this.refreshVerifyCode();
                                }
                            }, fail => {
                                $this.isLoginning = false;
                                $this.$message.error(fail.message);
                                if (fail.code !== 102) {
                                    $this.refreshVerifyCode();
                                }
                            });
                        }, error => {
                            $this.isLoginning = false;
                            $this.$message.error(error.message);
                        }, fail => {
                            $this.isLoginning = false;
                            $this.$message.error(fail.message);
                        });
                    } else {
                        $this.$message.error('请输入登录账户和密码');
                        $this.isLoginning = false;
                        return false;
                    }
                });
            },
            loginSuccess(userInfo){
                let $this = this;
                if ($this.$utils.isNotEmpty(userInfo.must_change_pwd) && userInfo.must_change_pwd === '1') {
                    $this.openChangePwdDialog(userInfo);
                    return;
                }
                // $this.$message.success('登录成功！');
                $this.$store.commit('setUserInfo', userInfo);
                $this.$utils.setSessionStorage($this.$store.state.storageName, userInfo);
                $this.$utils.setSessionStorage($this.$store.state.tokenName, userInfo.accessToken);
                // 记住密码
                if ($this.remember) {
                    let rememberUser = {
                        login_id: $this.param.login_id,
                        password: AES.en($this.param.password)
                    };
                    $this.$utils.setLocalStorage($this.$store.state.rememberUser, JSON.stringify(rememberUser));
                } else {
                    // 存在记住密码则删除
                    if ($this.$utils.getLocalStorage($this.$store.state.rememberUser)) {
                        $this.$utils.removeLocalStorage($this.$store.state.rememberUser);
                    }
                }
                // 初始化表格设置
                $this.$store.dispatch('initTableSetting');
                $this.$store.dispatch('initUserSetting', userInfo.sid);
                // END记住密码
                $this.$store.dispatch('initMenu').then(() => {
                    if (userInfo.url_after_logined && userInfo.url_after_logined.length>0){
                        $this.$router.push(userInfo.url_after_logined);
                    }else{
                        $this.$router.push('/dashboard');
                    }
                });
            },
            openChangePwdDialog(userInfo) {
                const _this = this;
                _this.$dialog({
                    title: '修改密码',
                    width: '400px',
                    appendToBody: true,
                    modal: true,
                    top: '0',
                    showClose: false,
                    noCloseBtn: true,
                    customClass: 'login_change_pwd_dialog',
                    closed() {
                        delete _this.param.verifyCode;
                        _this.isLoginning = false;
                        _this.refreshVerifyCode();
                    },
                    component: {
                        value: ModifyPwdForm,
                        props: {
                            data: userInfo,
                        },
                    },
                    confirmed() {
                        delete _this.param.verifyCode;
                        _this.isLoginning = false;
                        _this.refreshVerifyCode();
                    },
                });
            },
            toReg(){
                this.$router.push('/reg');
            },
        },
    };
</script>

<style lang="less" rel="stylesheet/less" scoped>
    .login-wrap {
        position: relative;
        width: 100%;
        height: 100%;
        background-image: url(../../assets/img/login-bg.jpg);
        background-size: 100%;

        .ms-login {
            position: absolute;
            left: 50%;
            top: 50%;
            width: 350px;
            margin: -300px 0 0 -175px;
            border-radius: 5px;
            background: rgba(255, 255, 255, 0.3);
            overflow: hidden;

            .ms-title {
                width: 100%;
                line-height: 50px;
                text-align: center;
                font-size: 20px;
                color: #409EFF;
                border-bottom: 1px solid #ddd;
                font-weight: bold;
            }

            .ms-content {
                padding: 30px 30px;
                /deep/.el-input-group__prepend{
                    // padding: 0;
                    // height: 32px;
                    // border: 0;
                    // .el-button{
                    //     // height: 24px;
                    //     border:1px solid #dcdfe6;
                    //     border-radius: 4px;
                    //     background-color: #F5F7FA;
                    //     color: #909399;
                    // }
                }
                .verifyCode {
                    /deep/.el-input-group__append {
                        width: 80px;
                        padding: 0;
                        line-height: 1;
                        height: 24px;
                        border:0;

                        .verify_img {
                            width: 100%;
                            height: 20px;
                        }
                    }
                }

                .login-btn {
                    margin-top: 10px;
                    text-align: center;

                    button {
                        width: 100%;
                        height: 36px;
                        margin-bottom: 10px;
                    }
                    .toReg{
                        margin-top: 20px;
                    }
                }
            }
        }

        .download_area {
            position: fixed;
            top: inherit;
            bottom: 40px;
            user-select: none;
            background: rgba(255, 255, 255);
            width: 220px;
            margin: -190px 0 0 -110px;

            .ms-content {
                text-align: center;
                padding: 10px;

                .el-image {
                    width: 200px;
                }

                .download_tips {
                    display: block;
                    font-size: 20px;
                    line-height: 30px;
                    color: #000;
                    cursor: pointer;

                    &:hover {
                        color: #409EFF;
                    }
                }
            }
        }
        .loginType{
            padding: 10px;
        }
    }
    #service_qr_lay{position:fixed;z-index:303;bottom:5em;right:5em;background-color:white;padding-bottom: 5px;}
    #bottom_layer{width:100%;position:fixed;z-index:302;bottom:0;left:0;height:39px;padding-top:1px;overflow:hidden;zoom:1;margin:0;line-height:39px;background:#fff}
    #bottom_layer .lh{display:inline;margin-right:20px}
    #bottom_layer .lh .emphasize{text-decoration:underline;font-weight:700}
    #bottom_layer .lh:last-child{margin-left:-2px;margin-right:0}
    #bottom_layer .lh.activity{font-weight:700;text-decoration:underline}
    #bottom_layer a{font-size:12px;text-decoration:none}
    #bottom_layer .text-color{color:#bbb}
    #bottom_layer .aria-img{width:49px;height:20px;margin-bottom:-5px}
    #bottom_layer a:hover{color:#222}
    #bottom_layer .s-bottom-layer-content{text-align:center}
    #bottom_layer .s-bottom-layer-content .auto-transform-line{display:inline}
    #bottom_layer .s-bottom-layer-content .auto-transform-line:first-child{margin-right:20px}
    #bottom_layer.ipad-bottom-layer{height:58px;line-height:22px;padding:7px 0;box-sizing:border-box}
    #bottom_layer.ipad-bottom-layer .s-bottom-layer-content .auto-transform-line{display:block;min-width:815px;overflow:hidden}
    #bottom_layer.ipad-bottom-layer .s-bottom-layer-content .auto-transform-line:first-child{margin-right:0}
</style>
